package controller

import (
	"data-system/excel"
	"data-system/meta"
	"data-system/models"
	"fmt"
	"log"

	"github.com/gin-gonic/gin"
	"github.com/thoas/go-funk"
)

var LoadedNodeTypes []string

func LoadLocalAllData(c *gin.Context) {
	req := struct {
		IsAll     bool     `json:"isAll"`
		NodeTypes []string `json:"nodeTypes"`
	}{}
	if err := c.Bind(&req); err != nil {
		log.Println(fmt.Errorf("参数解析异常,%v", err))
		c.JSON(models.FailData(err.Error()))
		return
	}
	var nodeTypes = meta.GetNodeTypes()
	if !req.IsAll {
		nodeTypes = req.NodeTypes
	}
	for _, nodeType := range nodeTypes {
		if req.IsAll == false && !funk.ContainsString(req.NodeTypes, nodeType) {
			continue
		}
		if funk.ContainsString(LoadedNodeTypes, nodeType) {
			continue
		}
		if !excel.IsConflict(nodeType) {
			isConflict, err := excel.ExcelToDB(nodeType, false)
			if err != nil {
				var errMsg string
				if isConflict {
					errMsg = "加载本地数据-excel同步db冲突：" + err.Error()
				} else {
					errMsg = "加载本地数据-excel同步db异常：" + err.Error()
				}
				log.Println(errMsg)
				c.JSON(models.FailData(errMsg))
				return
			}
		}
	}
	c.JSON(models.Ok())
}
